package com.easy.security.config;
import com.easy.security.filter.PermissionFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated()  // 其他请求需认证
                )
                .addFilterBefore(new PermissionFilter(), UsernamePasswordAuthenticationFilter.class)
                .formLogin().disable()
                .logout().disable()
                .csrf().disable();

        http.exceptionHandling(handling -> handling
                .accessDeniedHandler((request, response, ex) -> {
                    response.setStatus(403);
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write("{\"code\":403, \"msg\":\"权限不足\"}");
                })
        );

        return http.build();
    }
}
